package com.oristand.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author shiyjian
 * @version 1.0
 * @date 2021/12/25 11:26
 */
@Slf4j
@Controller
@RequestMapping(path = "/redis")
public class RedisLimitController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/go")
    public String go() {
        ReentrantLock lock = new ReentrantLock();
        try {
            lock.lock();
            Object value = redisTemplate.opsForValue().get("key");
            if (value != null) {
                Integer time = (Integer) value;
                if (time >= 3) {
                    return "false";
                } else {
                    redisTemplate.opsForValue().increment("key",1);
                    return "true";
                }
            } else {
                redisTemplate.opsForValue().set("key", 1, 10, TimeUnit.SECONDS);
                return "true";
            }
        } catch (Exception e){
            log.info("锁异常");
        } finally {
            lock.unlock();
        }
        return "false";
    }
}
